<template>
  <div>
    <el-row :gutter="20">
      <div class="app-container">
        <el-row type="flex" justify="start" align="middle">
          <el-col :span="4"
            ><span class="el-custom-title"
              >工艺组</span
            ></el-col
          >
          <el-col :span="20" style="float:right;">
            <el-button-group style="float: right">
              <el-button
                type="primary"
                icon="el-icon-download"
                class="el-button--mini"
                @click="handleImport"
                >导入</el-button
              >
              <el-button type="primary" 
                icon="el-icon-edit"
              
              size="mini" @click="handleUpdate()">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                  icon="el-icon-delete"
                @click="ui_delete(null, null)"
              >
                删除
              </el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start">
          <el-table
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChangeSon"
              ref="dataFormSon"
              >
             <el-table-column type="selection" width="55"></el-table-column>
                          <el-table-column
                            align="center"
                            label="序号"
                            width="95"
                            v-if="false"
                          >
                            <template slot-scope="scope">
                              {{ scope.row.id }}
                            </template>
                          </el-table-column>
                                            <el-table-column align="center" label="工艺组" width="95" style="display:none;">
                              <template slot-scope="scope">
                                {{ scope.row.technologySetName }}
                              </template>
                            </el-table-column>
                            <el-table-column align="center" label="工艺流程" width="95" style="display:none;">
                              <template slot-scope="scope">
                                {{ scope.row.technologyFlowName }}
                              </template>
                            </el-table-column>
                            <el-table-column align="center" label="序号" width="95" style="display:none;">
                              <template slot-scope="scope">
                                {{ scope.row.ordered }}
                              </template>
                            </el-table-column>
                            <el-table-column align="center" label="备注" width="95" style="display:none;">
                              <template slot-scope="scope">
                                {{ scope.row.comment }}
                              </template>
                            </el-table-column>
            </el-table>
         </el-row>
          <el-row>
           <pagination
            v-show="total2 > 0"
            :total="total2"
            :page.sync="listQuery2.page"
            :limit.sync="listQuery2.limit"
            :page-sizes="listQuery2.pageSizes"
             @pagination="fetchDataSon"
          />
        </el-row>
      </div>
    </el-row>
    

 <el-dialog :title="textMap[dialogStatusSon]" :visible.sync="dialogFormVisible">
      <el-form
        ref="FormSon"
        :rules="rulesson"
        :model="tempson"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
              <el-form-item label="工艺组Id" prop="technologySetId">
            <el-select-tree
            :default-expand-all="defaultExpandAll"
            :multiple="multiple"
            :placeholder="placeholder"
            :disabled="disabled"
            :data="lstAllTechnologySets"
            :props="defaultProps"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            v-model="tempson.technologySetId"
            @change="selectChange"
            show-checks
          ></el-select-tree>

              </el-form-item>
              <el-form-item label="工艺流程Id" prop="technologyFlowId">
                 <el-select-tree
            :default-expand-all="defaultExpandAll"
            :multiple="multiple"
            :placeholder="placeholder"
            :disabled="disabled"
            :data="data"
            :props="defaultPropSon"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            v-model="tempson.technologyFlowId"
            @change="selectChange"
            show-checks
          ></el-select-tree>
              </el-form-item>
              <el-form-item label="序号" prop="ordered">
                 <el-input-number v-model="tempson.ordered" :min="1" :max="10" label="序号"></el-input-number>
              </el-form-item>
              <el-form-item label="备注" prop="comment">
                <el-input v-model="tempson.comment" />
              </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title='textMap.import' :visible.sync="dialogImportVisible">
      <el-form
        ref="dataImport"
        :model="tempImport"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
       <el-row><el-col>
          <el-form-item label="父工艺组" prop="parentId">
            <el-select-tree
            :default-expand-all="defaultExpandAll"
            :multiple="multiple"
            :placeholder="placeholder"
            :disabled="disabled"
            :data="lstAllTechnologySets"
            :props="defaultProps"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            v-model="tempImport.parentId"
            @change="selectChange"
            show-checks
          ></el-select-tree>

        </el-form-item>
        
        </el-form-item></el-col><el-col> <el-form-item label="工段" prop="workSectionId">
          <el-select
            v-model="tempImport.workSectionId"
            class="filter-item"
            placeholder="请选择工段"
          >
            <el-option
              v-for="item in this.lstWorksections"
              :key="item.id"
              :label="item.workSectionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item></el-col><el-col>
        <el-button
          type="primary"
          @click="ui_query"
        >
          查询
        </el-button>
        </el-col>
        </el-row>
         
      </el-form>
      <div>
          <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            row-key="id" 
            ref="tableImport"
          >
            >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              align="center"
              label="工艺组编号"
              width="120"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.technologySetNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工艺组名称"
              width="120"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.technologySetName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="parentId"
              width="95"
              style="display:none;"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.parentId }}
              </template>
            </el-table-column>
             <el-table-column
              align="center"
              label="父组编号"
              width="95"
            >
              <template slot-scope="scope">
                {{ scope.row.parentNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="所属工段"
              width="100"
            >
              <template slot-scope="scope">
                {{ scope.row.workSectionName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="备注"
              width="95"
            >
              <template slot-scope="scope">
                {{ scope.row.comment }}
              </template>
            </el-table-column>
          </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="ui_import()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <router-view></router-view>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAll,
  getList,
  create,
  update,
  deleteBatch,
  getTable
} from "@/api/mesTechnologySet";

import {
  getAll as getAllSetFlow,
  getList as getListSetFlow,
  create as createSetFlow,
  createBatch as createBatchSetFlow,
  update as updateSetFlow,
  deleteBatch as deleteBatchSetFlow,
  getTable as getTableSetFlow
} from "@/api/mesTechnologySetFlow"


import {getAll as getAllWorksections} from '@/api/mesWorkSection'
import {getAllSon,getTable as getTableSon } from '@/api/mesTechnologyFlow'
import ElSelectTree from "el-select-tree";
export default {
  name:"mestechnologysetchild",
  components: { Pagination,ElSelectTree},
  data() {
    return {
      data: [],
      list: [],
      list2: null,
      listLoading: true,
      total: 0,
      total2: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      listQuery2: {
        page: 1,
        limit: 20,
        pageSizes: [20, 40, 60]
      },
     
      curMesTechnologyFlowId:0,
      dialogFormVisible: false,
      dialogImportVisible:false,
      dialogStatus: "",
      dialogStatusSon:"",
      textMap: {
        update: "编辑",
        create: "创建",
        import: "导入"
      },
      rulesson: {
               technologySetId: [
                 {
                   required: true,
                   message: "工艺组Id不能为空！",
                   trigger: "change",
                 },
               ],
               technologyFlowId: [
                 {
                   required: true,
                   message: "工艺流程Id不能为空！",
                   trigger: "change",
                 },
               ],
               ordered: [
                 {
                   required: true,
                   message: "序号不能为空！",
                   trigger: "change",
                 },
               ],
      },
      tempson: {
         id: 0,
              technologySetId : '',
              technologyFlowId : '',
              ordered : 0,
              comment : '',
      },
      tempImport:{
         workSectionId:0,
         parentId: 0
      },
      //表格變量
      lstSelected: [],
      lstTechnologySetIds: [],
      lstWorksections: [],
      lstAllTechnologySets:[],
      displayTree: false,
      clearable: true,
      defaultExpandAll: true,
      multiple: false,
      placeholder: "请选择",
      disabled: false,
      checkStrictly: true,
        defaultProps: {
        value: "id",
        children: "children",
        label: "technologySetName"
      },
      defaultPropSon: {
        value: "id",
        children: "children",
        label: "technologyFlowName"
      },
    };
  },
   props: { 
        mestechnologyflowid:{},
        mestechnologyflowids:{}
      },
  watch: {
     mestechnologyflowid: function(newVale,oldValue)
     {
       
       if(newVale != null && newVale != oldValue)
       {
          this.curMesTechnologyFlowId = newVale
          this.fetchDataSon()
       }
     },
     deep:true
  },
  created() {
    this.fetchData();
    this.fetchDataSon();
    this.getAllWorkSections()
    this.getAllMesTechnologySetIds()
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      let param = {}
      this.listLoading = true;
      getTable(param).then(response => {
        this.list = response.data.children;
        this.listLoading = false;
      });

      //获取全部的工艺组
      getTable({}).then(response => {
        this.lstAllTechnologySets = response.data.children;
        this.listLoading = false;
      });
       getTableSon().then(response => {
        this.data.length = 0;
        this.data.push(response.data);
        this.listLoading = false;
      });
      
    },
     fetchDataSon() {
       let param = {
         technologyFlowId:this.curMesTechnologyFlowId,
         page: this.listQuery2.page,
         size: this.listQuery2.limit
       }
      this.listLoading = true;
      this.list2 = [];
      getListSetFlow(param).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total
        this.listLoading = false;
         //通知父组件刷新
            this.$emit("refreshSteps",this.list2)
      });
    },
    rowClick(row, column, event) {
      this.currentTherbligsTypeId = row.id;
      //this.getTherbligs()
    },
    ui_import() {
      let selecteds = this.$refs.tableImport.selection
      let params = []
      if(selecteds == null || selecteds.length==0)
      {
           this.$message.error("请选择要导入的工艺组");
           return
      }
      params = params.concat(selecteds.map((itm) => {
         return {id:0,technologySetId: itm.id,technologyFlowId:this.curMesTechnologyFlowId,ordered:0,comment:''}
      }))
          createBatchSetFlow(params).then(() => {
            this.fetchDataSon()
            this.dialogImportVisible = false;
            this.$notify({
              title: "Success",
              message: "导入成功！",
              type: "success",
              duration: 2000
            });
          });
    },
    ui_update() {
      this.$refs["FormSon"].validate(valid => {
        if (valid) {
          updateSetFlow(this.tempson).then(() => {
            const index = this.list2.findIndex(v => v.id === this.tempson.id);
            this.list2.splice(index, 1, this.tempson);
            this.dialogFormVisible = false;
            //通知父组件刷新
            this.$emit("refreshSteps",this.list2)

            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      let selected = this.$refs.dataFormSon.selection
      if (selected == null || selected.length == 0) {
        this.$message.error("请先选择工艺组");
        return;
      }
      let ids = [];
      selected.map(function(elm) {
        ids.push(elm.id);
      });
     
      deleteBatchSetFlow(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list2.findIndex(v => v.id === elm);
          this.list2.splice(index, 1);
        });
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        technologySetNo: "",
        technologySetName: "",
        parentId: 0,
        workSectionId: "",
        comment: ""
      };
    },
    handleImport() {
      if(this.curMesTechnologyFlowId == 0)
      {
         this.$message.error("请先选择一条工艺流程");
        return;
      }
      this.resetTempImport();
      this.dialogStatus = "import";
      this.dialogImportVisible = true;
      this.$nextTick(() => {
        this.$refs["dataImport"].clearValidate();
      });
    },
    handleUpdate() {
      let selected = this.$refs.dataFormSon.selection
      if (selected == null || selected.length !== 1) {
        this.$message.error("请先选择一条工艺组");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["FormSon"].clearValidate();
      });
    },
    getAllMesTechnologySetIds()
    {
         this.lstTechnologySetIds.length = 0
         this.lstTechnologySetIds.push({id:0,name:"请选择"})
        //  this.getJosn(this.list)
         getTable({}).then(response=> {
             this.getJosn(response.data.children)
         })
         console.log(this.lstTechnologySetIds)
    },
    getJosn(arr)
    {
        if(arr != null && arr.length>0)
        {
            arr.forEach((itm) => {
                if(itm != null &&  itm instanceof Object)
                {
                   this.lstTechnologySetIds.push({id:itm.id,name:itm.technologySetName})
                   if(itm.children != null && itm.children.length>0)
                   this.getJosn(itm.children)
                }
            })
        }
    },
    getAllWorkSections()
    {
       this.lstWorksections.length = 0;
       this.lstWorksections.push({id:0,workSectionName:'请选择'})
       getAllWorksections({}).then(response=>{
         let r = response.data.map((itm) => {
            return {id:itm.id,workSectionName:itm.workSectionName}
         })
         this.lstWorksections =  this.lstWorksections.concat(r)
       })
    },
    resetTempImport()
    {
       this.tempImport =  { 
         workSectionId:0,
         parentId: 0
         }
    },
    ui_query()
    {
        this.fetchData(this.tempImport)
    },
    selectChange(){},

    handleSelectionChangeSon(val){
        if(val == null || val.length == 0) return
        let cur = this.list2.find(v =>
          v.id == val[0].id
        )
        if(cur != null)
        {
        this.tempson = Object.assign({},cur)
        }
    },
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
